package com.majun.huaxishe.utils;

import com.majun.huaxishe.constant.InfoConstant;
import com.majun.huaxishe.exception.UploadException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
public class FtpUtils {
    private static final String UPLOAD_DIRECTORY = "D:/huaxishe/deploy/html/img";

    public static String upload2Ftp(MultipartFile file, String albumName) {
        try {
            String realFilename = file.getOriginalFilename();
            String suffix = realFilename.substring(realFilename.lastIndexOf("."));

            // 拼接文件名
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            if (albumName != null) {
                fileName = albumName + "/" + fileName;
            }

            // 构建目标文件对象
            File destFile = new File(UPLOAD_DIRECTORY + File.separator + fileName);

            // 检查目标文件夹是否存在，如果不存在则创建
            File parentDir = destFile.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }

            // 将文件保存到目标位置
            file.transferTo(destFile);

            // 构建文件URL并返回
            return "http://192.168.0.152:9090/uploads/" + fileName;

        } catch (IOException e) {
            log.error(e.toString());
            throw new UploadException(InfoConstant.UPLOAD_FAIL);
        }
    }
}
